﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Lamex.Library;
using DevExpress.XtraCharts;
using System.Runtime.InteropServices;

namespace Lamex.mSchedule.UI
{
    public partial class frmSCH_Owed_Analyze_SubFactory : frmBaseChild
    {
        [DllImport("User32.dll")]
        private static extern IntPtr WindowFromPoint(Point p);

        public frmSCH_Owed_Analyze_SubFactory()
        {
            InitializeComponent();
        }

        private void frmSCH_Owed_Analyze_SubFactory_Resize(object sender, EventArgs e)
        {
            panel1.Height = this.Height / 2;
            panel2.Height = this.Height / 2;

            gcDesking.Width = panel1.Width / 2;
            gcSeating.Width = panel1.Width / 2;
            gcPanel.Width = panel2.Width / 2;
            gcTPF.Width = panel2.Width / 4;
            gcMCG.Width = panel2.Width / 4;

        }

        private void frmSCH_Owed_Analyze_SubFactory_Load(object sender, EventArgs e)
        {
            refreshData_By_PCS();
        }

        private void refreshData_By_PCS()
        {
            gcDesking.Text = "桌子（PCS）";
            gcSeating.Text = "椅子（PCS）";
            gcPanel.Text = "屏风（PCS）";
            gcTPF.Text = "铁屏风（PCS）";
            gcMCG.Text = "MCG（PCS）";

            setChartData_By_PCS(chrtBy_Desking, "OWED_QTY", "D", ViewType.Bar);
            setChartData_By_PCS(chrtBy_Seating, "OWED_QTY", "S", ViewType.Bar);
            setChartData_By_PCS(chrtBy_Panel, "OWED_QTY", "P", ViewType.Bar);
            setChartData_By_PCS(chrtBy_TPF, "OWED_QTY", "T", ViewType.Bar);
            setChartData_By_PCS(chrtBy_MCG, "OWED_QTY", "M", ViewType.Bar);
        }

        private void refreshData_By_Hours()
        {
            gcDesking.Text = "桌子（HOURS）";
            gcSeating.Text = "椅子（HOURS）";
            gcPanel.Text = "屏风（HOURS）";
            gcTPF.Text = "铁屏风（HOURS）";
            gcMCG.Text = "MCG（HOURS）";

            setChartData_By_PCS(chrtBy_Desking, "PROCESS_TIME", "D", ViewType.Bar);
            setChartData_By_PCS(chrtBy_Seating, "PROCESS_TIME", "S", ViewType.Bar);
            setChartData_By_PCS(chrtBy_Panel, "PROCESS_TIME", "P", ViewType.Bar);
            setChartData_By_PCS(chrtBy_TPF, "PROCESS_TIME", "T", ViewType.Bar);
            setChartData_By_PCS(chrtBy_MCG, "PROCESS_TIME", "M", ViewType.Bar);
        }

        private void setChartData_By_PCS(ChartControl chart, string strSum_Field, string strProcess_Type, ViewType vt)
        {
            string sql = "";

            if (strSum_Field == "PROCESS_TIME")
            {
                sql = @"  SELECT PROCESS_CODE, PROCESS_NAME, SUM(PROCESS_TIME)/3600 AS PROCESS_TIME
                  FROM View_OP_Follow_Process_Time
                  WHERE PROCESS_CODE LIKE '" + strProcess_Type + @"%'
                  GROUP BY PROCESS_CODE,PROCESS_NAME
                  ORDER BY PROCESS_CODE";
            }
            else
            {
                sql = @"  SELECT PROCESS_CODE, PROCESS_NAME, SUM(OWED_QTY) AS OWED_QTY
  FROM View_OP_Follow_Process_Time
  WHERE PROCESS_CODE LIKE '" + strProcess_Type + @"%'
  GROUP BY PROCESS_CODE,PROCESS_NAME
  ORDER BY PROCESS_CODE";
            }

            DataTable dt1 = Lamex.Base.BaseBuildSql.GetDataTableBySql(sql);
            if (dt1.Rows.Count != 0)
            {
                chart.Series.Clear();
                Series seriesAuto = new Series("", vt);

                foreach (DataRow dr in dt1.Rows)
                {
                    SeriesPoint p = new SeriesPoint();

                    //原值显示
                    if (dr["PROCESS_CODE"].ToString() != "")
                    {
                        double[] d = new double[] { double.Parse(Math.Round((decimal.Parse(dr[strSum_Field].ToString())), 0).ToString()) };
                        p.Values = d;
                        if (dr["PROCESS_NAME"].ToString().Length > 3)
                        {
                            p.Argument = dr["PROCESS_NAME"].ToString().Substring(0,3) + "...";
                        }
                        else
                        {
                            p.Argument = dr["PROCESS_NAME"].ToString();
                        }
                        seriesAuto.Points.Add(p);
                    }
                }

                chart.Series.Add(seriesAuto);
                chart.Legend.Visibility = DevExpress.Utils.DefaultBoolean.False;
                Legend Legends = (Legend)chart.Legend;
                Legends.Visibility = DevExpress.Utils.DefaultBoolean.True;
                Legends.AlignmentVertical = LegendAlignmentVertical.Top;
                Legends.AlignmentHorizontal = LegendAlignmentHorizontal.Left;
                Legends.TextVisible = true;

                //强制显示所有x轴标签
                XYDiagram diagram = ((XYDiagram)chart.Diagram);
                diagram.AxisX.QualitativeScaleOptions.AutoGrid = false;
                diagram.AxisX.Label.ResolveOverlappingOptions.AllowHide = false;

                //设置Series的标签
                seriesAuto.LabelsVisibility = DevExpress.Utils.DefaultBoolean.True;//每个点都显示数据
                //seriesAuto.ChangeView(ViewType.Bar);//设置图标显示的类型

                //设置标签的显示位置
                SideBySideBarSeriesLabel label = (SideBySideBarSeriesLabel)seriesAuto.Label;
                label.Position = BarSeriesLabelPosition.Top;

            }
        }

        private void tsOwed_By_PCS_Click(object sender, EventArgs e)
        {
            refreshData_By_PCS();
        }

        private void tsOwed_By_Hours_Click(object sender, EventArgs e)
        {
            refreshData_By_Hours();
        }

        private void tsOwed_By_HoursAndPCS_Click(object sender, EventArgs e)
        {
            refreshData_By_HoursAndPCS();
        }

        private void tsOwed_ChartPrint_Click(object sender, EventArgs e)
        {
            Point p = Cursor.Position;
            IntPtr h = WindowFromPoint(p);
            getControl_Handle(this, h.ToString());
            //chrtBy_Panel.OptionsPrint();
        }

        private void getControl_Handle(Control parentControl, string strPoint)
        {
            Control.ControlCollection childControls = parentControl.Controls;
            foreach (Control control in childControls)
            {
                if (control.Controls != null)
                {
                    if (control.Handle.ToString() == strPoint)
                    {
                        chartPrint(control.Name);
                        return;
                    }
                    else
                    {
                        getControl_Handle(control, strPoint);
                    }
                }
            }
        }

        private void chartPrint(string ctrlName)
        {
            switch (ctrlName)
            {
                case "chrtBy_Desking":
                    //chrtBy_Desking.ShowPrintPreview(DevExpress.XtraCharts.Printing.PrintSizeMode.Zoom);
                    chrtBy_Desking.OptionsPrint.SizeMode = DevExpress.XtraCharts.Printing.PrintSizeMode.Zoom;
                    chrtBy_Desking.ShowPrintPreview();
                    break;
                case "chrtBy_Seating":
                    //chrtBy_Seating.ShowPrintPreview(DevExpress.XtraCharts.Printing.PrintSizeMode.Zoom);
                    chrtBy_Seating.OptionsPrint.SizeMode = DevExpress.XtraCharts.Printing.PrintSizeMode.Zoom;
                    chrtBy_Seating.ShowPrintPreview();
                    break;
                case "chrtBy_Panel":
                    //chrtBy_Panel.ShowPrintPreview(DevExpress.XtraCharts.Printing.PrintSizeMode.Zoom);
                    chrtBy_Panel.OptionsPrint.SizeMode = DevExpress.XtraCharts.Printing.PrintSizeMode.Zoom;
                    chrtBy_Panel.ShowPrintPreview();
                   break;
                case "chrtBy_TPF":
                    //chrtBy_TPF.ShowPrintPreview(DevExpress.XtraCharts.Printing.PrintSizeMode.Zoom);
                    chrtBy_TPF.OptionsPrint.SizeMode = DevExpress.XtraCharts.Printing.PrintSizeMode.Zoom;
                    chrtBy_TPF.ShowPrintPreview();
                    break;
                case "chrtBy_MCG":
                    //chrtBy_MCG.ShowPrintPreview(DevExpress.XtraCharts.Printing.PrintSizeMode.Zoom);
                    chrtBy_MCG.OptionsPrint.SizeMode = DevExpress.XtraCharts.Printing.PrintSizeMode.Zoom;
                    chrtBy_MCG.ShowPrintPreview();
                   break;
                default:
                    break;
            }
        }

        private void refreshData_By_HoursAndPCS()
        {

            gcDesking.Text = "桌子";
            gcSeating.Text = "椅子";
            gcPanel.Text = "屏风";
            gcTPF.Text = "铁屏风";
            gcMCG.Text = "MCG";

            #region 使用ChartControl绘制多重坐标图形：
            //https://blog.csdn.net/NarutoInspire/article/details/48489809

            //创建几个图形的对象
            //Series series1 = CreateSeries("员工人数", ViewType.Line, dt, 0);
            //Series series2 = CreateSeries("人均月薪", ViewType.Line, dt, 1);
            //Series series3 = CreateSeries("成本TEU", ViewType.Line, dt, 2);
            //Series series4 = CreateSeries("人均生产率", ViewType.Line, dt, 3);
            //Series series5 = CreateSeries("占2005年3月人数比例", ViewType.Line, dt, 4);

            //List<series> list = new List<series>() { series1, series2, series3, series4, series5 };
            //chartControl1.Series.AddRange(list.ToArray());
            //chartControl1.Legend.Visible = false;
            //chartControl1.SeriesTemplate.LabelsVisibility = DefaultBoolean.True;
            //for (int i = 0; i < list.Count; i++)
            //{
            //    list[i].View.Color = colorList[i];
            //    CreateAxisY(list[i]);
            //}

            #endregion

        }

        #region 使用ChartControl绘制多重坐标图形：
        /// <summary>
        /// 根据数据创建一个图形展现
        /// </summary>
        /// <param name="caption">图形标题
        /// <param name="viewType">图形类型
        /// <param name="dt">数据DataTable
        /// <param name="rowIndex">图形数据的行序号
        /// <returns></returns>
        private Series CreateSeries(string caption, ViewType viewType, DataTable dt, int rowIndex)
        {
            Series series = new Series(caption, viewType);
            for (int i = 1; i < dt.Columns.Count; i++)
            {
                string argument = dt.Columns[i].ColumnName;//参数名称
                decimal value = (decimal)dt.Rows[rowIndex][i];//参数值
                series.Points.Add(new SeriesPoint(argument, value));
            }

            //必须设置ArgumentScaleType的类型，否则显示会转换为日期格式，导致不是希望的格式显示
            //也就是说，显示字符串的参数，必须设置类型为ScaleType.Qualitative
            series.ArgumentScaleType = ScaleType.Qualitative;
            series.LabelsVisibility = DevExpress.Utils.DefaultBoolean.True;//显示标注标签
            return series;
        }

        /// <summary>
        /// 创建图表的第二坐标系
        /// </summary>
        /// <param name="series">Series对象
        /// <returns></returns>
        //private SecondaryAxisY CreateAxisY(Series series)
        //{
        //    SecondaryAxisY myAxis = new SecondaryAxisY(series.Name);
        //    ((XYDiagram)chartControl1.Diagram).SecondaryAxesY.Add(myAxis);
        //    ((LineSeriesView)series.View).AxisY = myAxis;
        //    myAxis.Title.Text = series.Name;
        //    myAxis.Title.Alignment = StringAlignment.Far; //顶部对齐
        //    myAxis.Title.Visible = true; //显示标题
        //    myAxis.Title.Font = new Font("宋体", 9.0f);
        //    Color color = series.View.Color;//设置坐标的颜色和图表线条颜色一致
        //    myAxis.Title.TextColor = color;
        //    myAxis.Label.TextColor = color;
        //    myAxis.Color = color;
        //    return myAxis;
        //}
        #endregion

        #region 两种遍历窗体控件方法
        //用递归方法遍历获取控件
        private void GetControlsByRecursion(Control parentControl)
        {
            Control.ControlCollection childControls = parentControl.Controls;
            foreach (Control control in childControls)
            {
                //listBox1.Items.Add(control.Name + "^" + control.GetType().Name.ToString());
                if (control.Controls != null)
                {
                    if (control.Name == "groupControl1")
                    {
                        //MessageBox.Show("groupControl1");
                        //return;
                    }
                    else
                    {
                        GetControlsByRecursion(control);
                    }
                }
            }
        }

        //用反射方法遍历获取控件及组件
        private void GetControlsByReflection()
        {
            System.Reflection.FieldInfo[] fieldInfo = this.GetType().GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            for (int i = 0; i < fieldInfo.Length; i++)
            {
                //listBox1.Items.Add(fieldInfo[i].Name + "^" + fieldInfo[i].GetType().Name.ToString());
            }
        }
        #endregion
    }
}